const {  $, $fn } = window
import { dataTypeData } from './mysql-data'
/* -------------------------------------------------------- -- */
export const modType = ({ database, table_name, data, e, tableRef }) => {
	e.stopPropagation()
	const config = {
		modal:{
			title 	: <span>修改字段【<b className='c3 ar'>{data.Field}</b>】数据类型</span>,
			width 	: '50%',
		},
		form: {
			labelWidth: 's6',
			// api: 'mysql/structure/mod_type',
			api: 'mysql/structure/mod_field',
			way:'put',
			infoApi : false,
			param: { database, table_name, ...data, change:false, y:2 },
			setParam: ({ Type, y }) => ({ y: Type.includes('_len') ? null : y }),
			data: [
				{ label: '字段名', 		name: 'Field', disabled:1 },
				{ label: '数据类型',		name: 'Type', type:'select', data: dataTypeData, r:1, group:1, listHeight:600, change: v => changeType({ ...v, config })},
				{ label: '长度',		name: 'x', type:'number', r:1 },
				{ label: '小数位数',		name: 'y', type:'number', r:1, half:1 },
			],
			onOk : () => {
				$.ref(tableRef).tableRef().search({ scroll:0 })
			}
		},
		onEnd:({ formRef, update }) => {
			const back = backType({ Type:data.Type, config })
			formRef.setValue(back)
			update()
		}
	}
	window.$formModalRef().open(config)
}

export const changeType = ({ value, ref, row, config }) => {
	let { def, extra, range } = row
	let _def = {}
	let _extra = {}
	if(def) _def = { Default: def }
	if(extra) _extra = { Extra: extra }
	const _x = $fn.getRow( config, 'x')
	const _y = $fn.getRow( config, 'y')
	const is_x = value.includes('_len')
	const is_y = ['decimal_len', 'numeric_len'].includes(value)
	_x.hide = !is_x
	_y.hide = !is_y
	_x.half = is_x && is_y
	_x.disabled = !is_x
	// 验证
	if( range ) {
		_x.range = range
	}
	ref.setValue({ ..._def, ..._extra, y: is_y ? 2 : null })
	//
	ref.update()
}
export const backType = ({ Type, config }) => {
	const reg = /\([\d\s,]+\)/g
	let x = null
	let y = null
	let type = Type
	if( reg.test(Type)){
		type = Type.replace(reg, '')
		let m = Type.match( reg )
		if( $fn.hasArray(m) ){
			let s = m[0]
			s = s.replace('(','')
			s = s.replace(')','')
			s = s.split(',')
			x = +s[0]
			y = +s?.[1]
		}
	}
	
	let _x = $fn.getRow(config, 'x')
	let _y = $fn.getRow(config, 'y')
	
	if( !Type.includes(',') ) { y = null }
	
	if( x || y) {
		if( x && Type === 'char(1)' ) {
			_x.disabled = 1
		}else{
			type = type + '_len'
		}
	}
	
	_x.hide = !reg.test(Type)
	_y.hide = !Type.includes(',')
	_x.half = x && y
	return { Type:type, x, y }
}